<template>
  <div class="favorite-jobs">
    <div class="section-header">
      <div class="left">
        <h3 class="section-title">收藏的职位</h3>
        <div class="job-count">共 {{ totalJobs }} 个职位</div>
      </div>
      <div class="right">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索职位名称或公司"
          clearable
          class="search-input"
        >
          <template #prefix>
            <el-icon><search /></el-icon>
          </template>
        </el-input>
      </div>
    </div>
    
    <div class="job-list" v-loading="loading">
      <el-row :gutter="20">
        <el-col 
          :xs="24" 
          :sm="12" 
          :md="8" 
          v-for="(job, index) in filteredJobs" 
          :key="`job-${job.id || index}`"
          class="job-col"
        >
          <el-card shadow="hover" class="job-card">
            <div class="card-header">
              <div class="job-title" @click="viewJobDetail(job.id)">{{ job.title }}</div>
              <div class="job-salary">{{ job.salary }}</div>
            </div>
            
            <div class="company-info">
              <div class="company-name">{{ job.companyName || job.company }}</div>
              <div class="job-meta">
                <span class="location">{{ job.city || job.location }}</span>
                <span class="divider">·</span>
                <span class="experience">{{ job.experience || '经验不限' }}</span>
              </div>
            </div>
            
            <div class="job-tags">
              <el-tag 
                v-for="(tag, tagIndex) in job.tags" 
                :key="`tag-${tagIndex}`"
                size="small"
                effect="plain"
              >
                {{ tag }}
              </el-tag>
            </div>
            
            <div class="card-footer">
              <div class="collection-time">
                收藏于 {{ formatDate(job.collectTime || job.createTime) }}
              </div>
              <div class="actions">
                <el-button
                  type="danger"
                  plain
                  size="small"
                  @click="removeFromFavorites(job.id)"
                >
                  取消收藏
                </el-button>
                
                <el-button
                  type="primary"
                  plain
                  size="small"
                  @click="applyJob(job.id)"
                >
                  申请职位
                </el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
      
      <el-empty 
        v-if="filteredJobs.length === 0 && !loading" 
        description="暂无收藏的职位" 
      >
        <el-button type="primary" @click="goToJobList">
          去浏览职位
        </el-button>
      </el-empty>
    </div>
    
    <!-- 分页 -->
    <div class="pagination-container" v-if="totalJobs > 0">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[12, 24, 36, 48]"
        :layout="'total, sizes, prev, pager, next, jumper'"
        :total="totalJobs"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { getFavoriteJobs, removeFromFavorite } from '@/api/personal'
import { applyJob as applyForJob } from '@/api/job'

const router = useRouter()

// 状态变量
const loading = ref(false)
const searchKeyword = ref('')
const favoriteJobs = ref([])
const searchTimeout = ref(null)

// 分页参数
const currentPage = ref(1)
const pageSize = ref(12)
const total = ref(0)

// 总职位数
const totalJobs = computed(() => total.value)

// 筛选后的职位
const filteredJobs = computed(() => favoriteJobs.value)

// 监听搜索关键词变化
watch(searchKeyword, (newValue) => {
  // 清除之前的定时器
  if (searchTimeout.value) {
    clearTimeout(searchTimeout.value)
  }
  
  // 设置新的定时器，防抖处理
  searchTimeout.value = setTimeout(() => {
    currentPage.value = 1 // 搜索时重置到第一页
    fetchFavoriteJobs()
  }, 300)
})

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  
  const date = new Date(dateString)
  const now = new Date()
  const diff = now - date
  
  // 一天内
  if (diff < 86400000) {
    return '今天'
  }
  
  // 一周内
  if (diff < 604800000) {
    const days = Math.floor(diff / 86400000)
    return `${days}天前`
  }
  
  // 一个月内
  if (diff < 2592000000) {
    const weeks = Math.floor(diff / 604800000)
    return `${weeks}周前`
  }
  
  // 超过一个月显示具体日期
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  fetchFavoriteJobs()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchFavoriteJobs()
}

// 查看职位详情
const viewJobDetail = (jobId) => {
  router.push(`/jobs/${jobId}`)
}

// 去职位列表页
const goToJobList = () => {
  router.push('/jobs')
}

// 申请职位
const applyJob = async (jobId) => {
  try {
    loading.value = true
    const res = await applyForJob(jobId, { resumeId: null }) // 需要选择简历ID，此处先传空
    
    if (res && res.code === 200) {
      ElMessage.success('申请成功，请到申请记录中查看')
      router.push('/personal?tab=applications')
    } else {
      ElMessage.error(res?.message || '申请失败')
      // 跳转到职位详情页，让用户选择简历再申请
      router.push(`/jobs/${jobId}?apply=true`)
    }
  } catch (error) {
    console.error('申请职位失败', error)
    ElMessage.error('申请失败，请在职位详情页选择简历后申请')
    router.push(`/jobs/${jobId}?apply=true`)
  } finally {
    loading.value = false
  }
}

// 从收藏中移除
const removeFromFavorites = async (jobId) => {
  try {
    await ElMessageBox.confirm(
      '确定要移除此收藏职位吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    loading.value = true
    const res = await removeFromFavorite(jobId)
    
    if (res && res.code === 200) {
      favoriteJobs.value = favoriteJobs.value.filter(job => job.id !== jobId)
      total.value = Math.max(0, total.value - 1)
      ElMessage.success('已从收藏中移除')
      
      // 如果当前页已经没有数据了，且不是第一页，则回到上一页
      if (favoriteJobs.value.length === 0 && currentPage.value > 1) {
        currentPage.value--
        fetchFavoriteJobs()
      }
    } else {
      ElMessage.error(res?.message || '操作失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('移除收藏失败', error)
      ElMessage.error('操作失败，请重试')
    }
  } finally {
    loading.value = false
  }
}

// 获取收藏职位数据
const fetchFavoriteJobs = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      keyword: searchKeyword.value || undefined
    }
    
    const res = await getFavoriteJobs(params)
    
    if (res && res.code === 200) {
      // 处理返回的数据
      favoriteJobs.value = res.data.records.map(job => ({
        ...job,
        // 确保tags是数组
        tags: job.tags ? job.tags.split(',').map(tag => tag.trim()).filter(Boolean) : []
      }))
      total.value = res.data.total || favoriteJobs.value.length
    } else {
      ElMessage.error(res?.message || '获取收藏数据失败')
    }
  } catch (error) {
    console.error('获取收藏职位失败', error)
    ElMessage.error('获取收藏职位失败')
  } finally {
    loading.value = false
  }
}

// 初始化
onMounted(() => {
  fetchFavoriteJobs()
})
</script>

<style lang="scss" scoped>
@import '@/assets/styles/variables.css';

.favorite-jobs {
  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: var(--spacing-lg);
    
    .left {
      display: flex;
      align-items: baseline;
      
      .section-title {
        font-size: 1.2rem;
        font-weight: 600;
        color: var(--text-primary);
        margin: 0;
        margin-right: var(--spacing-sm);
      }
      
      .job-count {
        color: var(--text-secondary);
        font-size: 0.9rem;
      }
    }
    
    .right {
      .search-input {
        width: 250px;
      }
    }
  }
  
  .job-list {
    min-height: 300px;
    
    .job-col {
      margin-bottom: var(--spacing-lg);
    }
    
    .job-card {
      height: 100%;
      
      .card-header {
        display: flex;
        justify-content: space-between;
        margin-bottom: var(--spacing-sm);
        
        .job-title {
          font-size: 1.1rem;
          font-weight: 600;
          color: var(--text-primary);
          cursor: pointer;
          
          &:hover {
            color: var(--primary-color);
          }
        }
        
        .job-salary {
          color: #f56c6c;
          font-weight: 500;
        }
      }
      
      .company-info {
        margin-bottom: var(--spacing-sm);
        
        .company-name {
          color: var(--text-secondary);
          margin-bottom: 4px;
        }
        
        .job-meta {
          font-size: 0.9rem;
          color: var(--text-secondary);
          
          .divider {
            margin: 0 4px;
          }
        }
      }
      
      .job-tags {
        margin-bottom: var(--spacing-md);
        min-height: 32px;
        
        .el-tag {
          margin-right: var(--spacing-xs);
          margin-bottom: var(--spacing-xs);
        }
      }
      
      .card-footer {
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-top: 1px solid var(--border-color-light);
        padding-top: var(--spacing-sm);
        
        .collection-time {
          font-size: 0.9rem;
          color: var(--text-secondary);
        }
        
        .actions {
          display: flex;
          gap: var(--spacing-sm);
        }
      }
    }
  }
}

// 响应式适配
@media (max-width: 768px) {
  .favorite-jobs {
    .section-header {
      flex-direction: column;
      align-items: flex-start;
      
      .left {
        margin-bottom: var(--spacing-sm);
      }
      
      .right {
        width: 100%;
        
        .search-input {
          width: 100%;
        }
      }
    }
    
    .job-card {
      .card-footer {
        flex-direction: column;
        align-items: flex-start;
        
        .collection-time {
          margin-bottom: var(--spacing-sm);
        }
        
        .actions {
          width: 100%;
          justify-content: space-between;
        }
      }
    }
  }
}
</style> 